
package com.be.beadmin.device.impl;

import com.be.beadmin.common.entity.FilderExpressEntity;
import com.be.beadmin.common.entity.PageEntity;
import com.be.beadmin.common.entity.SortExpressEntity;
import com.be.beadmin.device.dto.output.InspectStandardEx;
import com.be.beadmin.device.entity.*;
import cn.hutool.core.util.ObjectUtil;

import com.be.beadmin.common.exception.BeadminException;
import com.be.beadmin.common.utils.JpaQueryBuilder;
import com.be.beadmin.common.utils.JpaSortBuilder;
import com.be.beadmin.device.mapper.*;
import com.be.beadmin.device.repository.InspectStandardRepository;
import com.be.beadmin.device.repository.InspectSubItemRepository;
import lombok.RequiredArgsConstructor;
import com.be.beadmin.device.repository.InspectPlanRepository;
import com.be.beadmin.device.service.InspectPlanService;
import com.be.beadmin.device.dto.input.InspectPlanDto;
import com.be.beadmin.device.dto.output.InspectPlanEx;
import org.springframework.stereotype.Service;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;

import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Order;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * @description 服务实现
 * @author chenxu
 * @date 2023-09-18
 **/
@Service
@RequiredArgsConstructor
public class InspectPlanServiceImpl implements InspectPlanService {

    @Autowired
    private  InspectPlanRepository inspectPlanRepository;
    @Autowired
    private  InspectPlanMapper inspectPlanMapper;
    @Autowired
    private  InspectPlanMapperEx inspectPlanExMapper;

    @Override
    public Page<InspectPlanEx> getInspectPlanByPage(PageEntity pageEntity) {
        Pageable pageable = PageRequest.of(
                pageEntity.getCurrent() -1,
                pageEntity.getPageSize());
        Page<InspectPlan> page = inspectPlanRepository.findAll((root, criteriaQuery, criteriaBuilder) -> {
                    List<Predicate> list = new ArrayList<>();
                    Predicate pre1 =   JpaQueryBuilder.getPredicate(root, pageEntity.getFilters(), criteriaBuilder);
                    list.add(pre1);
                    Predicate pre2 = criteriaBuilder.equal(root.get(InspectPlan_.delete), 0); //过滤为0
                    list.add(pre2);
                    Predicate[] p = new Predicate[list.size()];
                    List<Order> orders = new ArrayList<>();
                    if(pageEntity.getSorters() != null && pageEntity.getSorters().size() > 0) {
                        orders = JpaSortBuilder.getPredicate(root, pageEntity.getSorters(), criteriaBuilder);
                        criteriaQuery.orderBy(orders);
                    } else {
                        criteriaQuery.orderBy(criteriaBuilder.desc(root.get(InspectPlan_.createTime).as(Date.class)));
                    }
                    return  criteriaBuilder.and(list.toArray(p));
                }
                , pageable);
        Page<InspectPlanEx> page1 = page.map(inspectPlanExMapper::toEntity);
        return page1;

    }

    @Override
    public void addInspectPlan(InspectPlanDto inspectPlanDto) {
        InspectPlan result = inspectPlanRepository.findInspectPlanByIdAndDelete(inspectPlanDto.getId(), 0);
        if(ObjectUtil.isNotEmpty(result)) {
            throw new BeadminException("InspectPlan不存在,请重新查询");
        }
        InspectPlan inspectPlan = inspectPlanMapper.toEntity(inspectPlanDto);
        inspectPlan.setInspectID(inspectPlanDto.getInspectID());
        inspectPlan.setTemplateID(inspectPlanDto.getTemplateID());
        inspectPlanRepository.save(inspectPlan);
    }

    @Override
    public void updateInspectPlan(InspectPlanDto inspectPlanDto) {
        InspectPlan inspectPlan = inspectPlanRepository.findInspectPlanById(inspectPlanDto.getId());
        inspectPlan = inspectPlanMapper.toEntity(inspectPlanDto);
        inspectPlanRepository.save(inspectPlan);
    }


    @Override
    public void delInspectPlan(String id) {
        InspectPlan inspectPlan = inspectPlanRepository.findInspectPlanById(id);
        inspectPlan.setDelete(1);
        inspectPlanRepository.save(inspectPlan);
    }






    @Autowired
    private  InspectStandardRepository inspectStandardRepository;
    @Autowired
    private InspectStandardMapper inspectStandardMapper;
    @Autowired
    private InspectStandardMapperEx inspectStandardExMapper;
    @Autowired
    private InspectSubItemRepository inspectSubItemRepository;
    @Autowired
    private InspectSubItemMapper inspectSubItemMapper;
    @Override
    public Map<String,String> getInspectId(PageEntity pageEntity)
    {
        String InspectId=null;
        pageEntity.setCurrent(1);
        pageEntity.setPageSize(20);
        Page<InspectPlanEx> planpage=getInspectPlanByPage(pageEntity);
        int id=1;
        LocalDate currentDate = LocalDate.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
        String formattedDate = currentDate.format(formatter);

        while (true) {
            String strDate = formattedDate;
            strDate ="YJ"+ strDate + "." + id;
            boolean found = true;
            for (InspectPlanEx inspectPlanEx : planpage.getContent()) {
                if (strDate.equals(inspectPlanEx.getInspectID())) {
                    found=false;
                    break;
                }
            }
            if(!found) {
                found=true;
                id++;
            }
            else {
                break;
            }
        }

        InspectId="YJ"+formattedDate+"."+id;
        Map<String, String> map = new HashMap<>();
        map.put("InspectId",InspectId);
        return map;
    }

    @Override
    public void receiveInspectSubItem(InspectPlanDto inspectPlanDto)
    {
        PageEntity pageEntity=new PageEntity();
        pageEntity.setCurrent(1);
        pageEntity.setPageSize(50);
        List<FilderExpressEntity> filters=new ArrayList<>();
        List<SortExpressEntity> sorters = new ArrayList<>();
        if (inspectPlanDto.getTemplateID()!=null){
            FilderExpressEntity filter = new FilderExpressEntity();
            filter.setField("templateId");
            filter.setOperator("eq");
            filter.setValue(inspectPlanDto.getTemplateID());
            filter.setAndOr("and");
            filters.add(filter);
        }
        pageEntity.setFilters(filters);
        pageEntity.setSorters(sorters);
        Page<InspectStandardEx> inspectstandardpage=getInspectStandardByPage(pageEntity);
        for (InspectStandardEx inspectStandardEx : inspectstandardpage.getContent()) {
            InspectSubItem inspectSubItem = new InspectSubItem();
            inspectSubItem.setInspectID(inspectPlanDto.getInspectID());
            inspectSubItem.setCheckItem(inspectStandardEx.getCheckItem());
            inspectSubItem.setNotes(inspectStandardEx.getNotes());
            inspectSubItem.setIdentification(inspectStandardEx.getIdentification());
            inspectSubItem.setCheckDesc(inspectStandardEx.getCheckDesc());
            inspectSubItem.setIsValid(inspectStandardEx.getIsValid());
            inspectSubItem.setSequence(inspectStandardEx.getSequence());
            inspectSubItem.setIsAttached(inspectStandardEx.getIsAttached());
            inspectSubItemRepository.save(inspectSubItem);
        }
    }
    @Override
    public Page<InspectStandardEx> getInspectStandardByPage(PageEntity pageEntity) {
        Pageable pageable = PageRequest.of(
                pageEntity.getCurrent() -1,
                pageEntity.getPageSize());
        Page<InspectStandard> page = inspectStandardRepository.findAll((root, criteriaQuery, criteriaBuilder) -> {
                    List<Predicate> list = new ArrayList<>();
                    Predicate pre1 =   JpaQueryBuilder.getPredicate(root, pageEntity.getFilters(), criteriaBuilder);
                    list.add(pre1);
                    Predicate pre2 = criteriaBuilder.equal(root.get(InspectStandard_.delete), 0); //过滤为0
                    list.add(pre2);
                    Predicate[] p = new Predicate[list.size()];
                    List<Order> orders = new ArrayList<>();
                    if(pageEntity.getSorters() != null && pageEntity.getSorters().size() > 0) {
                        orders = JpaSortBuilder.getPredicate(root, pageEntity.getSorters(), criteriaBuilder);
                        criteriaQuery.orderBy(orders);
                    } else {
                        criteriaQuery.orderBy(criteriaBuilder.desc(root.get(InspectStandard_.createTime).as(Date.class)));
                    }
                    return  criteriaBuilder.and(list.toArray(p));
                }
                , pageable);
        Page<InspectStandardEx> page1 = page.map(inspectStandardExMapper::toEntity);
        return page1;

    }
    @Override
    public void delInspectPlans (List<String> ids) { }

    //获取巡检人
    @Override
    public List<String> getInspectByList() {
        List<String> inspectBys = new ArrayList<>();
        List<InspectPlan> inspectPlans = inspectPlanRepository.findInspectPlansByDelete(0);
        for (int i = 0; i < inspectPlans.size(); i++) {
            String inspect = inspectPlans.get(i).getInspectBy();
            inspectBys.add(inspect);
        }

        return inspectBys;
    }


}

